//
//  ZslanguageTool.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/4/22.
//

import UIKit

class ZslanguageTool: NSObject {
    
    var allkeysEN:Array<String>!
    var allkeysCH:Array<String>!
    var allkeysBU:Array<String>!

    var dicDicCH:Dictionary<String,String>!
    var dicDicEN:Dictionary<String,String>!
    var dicDicBU:Dictionary<String,String>!
    
    static let instance : ZslanguageTool = ZslanguageTool()
    class func sharedLanguageTool() -> ZslanguageTool {
        
        let pathCH = Bundle.main.path(forResource: "languageCH", ofType: "json")
        let pathBU = Bundle.main.path(forResource: "languageBU", ofType: "json")
        let pathEN = Bundle.main.path(forResource: "languageEN", ofType: "json")

        let dataCH = try! NSData.init(contentsOfFile: pathCH!) as Data
        let dataEN = try! NSData.init(contentsOfFile: pathEN!) as Data
        let dataBU = try! NSData.init(contentsOfFile: pathBU!) as Data

        instance.dicDicCH = try! JSONSerialization.jsonObject(with: dataCH, options: JSONSerialization.ReadingOptions.mutableLeaves) as! Dictionary<String, String>
        instance.dicDicEN = try! JSONSerialization.jsonObject(with: dataEN, options: JSONSerialization.ReadingOptions.mutableLeaves) as! Dictionary<String, String>
        instance.dicDicBU = try! JSONSerialization.jsonObject(with: dataBU, options: JSONSerialization.ReadingOptions.mutableLeaves) as! Dictionary<String, String>

        instance.allkeysEN = Array(instance.dicDicEN.keys)
        instance.allkeysCH = Array(instance.dicDicCH.keys)
        instance.allkeysBU = Array(instance.dicDicBU.keys)

        return instance
    }
    
    func getIanguageWithKey(key:String) -> String {
        let str = UserDefaults.standard.string(forKey:LanguageHeader.MySystemLanguage)
        if (str == LanguageHeader.ChinaLanguage) {
            if (self.allkeysCH.contains(key)) {
                return self.dicDicCH[key] ?? ""
            }
        } else if (str == LanguageHeader.BurmaLanguage) {
            if (self.allkeysBU.contains(key)) {
                return self.dicDicBU[key] ?? ""
            }
        } else {
            if (self.allkeysEN.contains(key)) {
                return self.dicDicEN[key] ?? ""
            }
        }
        return "unfound"
    }
    
    func getSystemLanguage() -> String {
        let ary:Array = UserDefaults.standard.object(forKey: "AppleLanguages") as! Array<Any>
        var languageCode:String = "";
        if ary.count > 0 {
            languageCode = ary[0] as! String
        }
        if languageCode == LanguageHeader.USALanguage || languageCode == LanguageHeader.ChinaLanguage || languageCode == LanguageHeader.BurmaLanguage {
            return languageCode
        }
        return LanguageHeader.BurmaLanguage
    }
}
